<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>张鑫旭</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <input type="file" id="file" multiple="multiple"></input>
    <script>
        let eleFile = document.querySelector('#file');

        let img = new Image();

        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');


        let reader = new FileReader(); // FileReader 是 html5 之后新加的读取本地文件的对象
        reader.onload = function(e) { // 文件加载后执行这个函数
            // console.log(e.target.result);
            img.src = e.target.result;
            document.body.append(img);
            
        }

        // 监听图片加载
        img.onload = function() {
            let originWidth = this.width;
            let originHeight = this.height;
            let maxWidth = 400;
            let maxHeight = 400;
            let targetWidth = originWidth,targetHeight = originHeight;

            // 变换图片大小
            if( originWidth > maxWidth || originHeight > maxHeight) {
                if( originWidth / originHeight > maxWidth / maxHeight) {
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxHeight * (originHeight / originWidth));

                }else {
                    targetHeight = maxHeight;
                    targetWidth = Math.round( maxWidth * ( originWidth / originHeight));
                }
            }

            // 利用 canvas 压缩图片
            canvas.width = targetWidth;
            canvas.height = targetHeight;

            context.drawImage(img,0,0,targetWidth,targetHeight); // 放置图片在canvas;
            document.body.appendChild(canvas);
            
            console.log(originWidth,originHeight);
        }

        eleFile.addEventListener('change',function(event) {
            console.log(event.target.files)
            file = event.target.files[0];
            if(file.type.indexOf('image') === 0) { // 如果选的是图片, string.indexOf() ?
                reader.readAsDataURL(file); // 将文件转换成 base64 格式

            }
        })

    </script>
</body>
</html>